#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#define N 32

#define ERRLOG(errmsg) do{\
                                                            perror(errmsg);\
                                                            printf("file:%s,func:%s,line:%d\n",__FILE__,__func__,__LINE__);\
                                                            exit(-1);\
                                                            }while(0);

int main(int argc, char const *argv[])
{
    int sockfd=-1;
    int acceptfd=-1;
    struct sockaddr_in servaddr,clientaddr;
    socklen_t len=sizeof(servaddr);
    if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){
        ERRLOG("socket error");
    }    

    servaddr.sin_family=AF_INET;
    servaddr.sin_port=htons(atoi(argv[1]));
    servaddr.sin_addr.s_addr=inet_addr(argv[2]);

    if(bind(sockfd,(struct sockaddr*)&servaddr,len)==-1){
        ERRLOG("bind error");
    }

    if(listen(sockfd,5)==-1){
        ERRLOG("listen error");
    }

out:
    if((acceptfd=accept(sockfd,(struct sockaddr*)&clientaddr,&len))==-1){
        ERRLOG("accept error");
    }

    printf("client:[%s][%d] 连接\n",inet_ntoa(clientaddr.sin_addr),ntohs(clientaddr.sin_port));

    char buf[N]={0};
    char filename[N]={0};
    ssize_t recvbytes,readbytes;
    int fd=-1;
    while(1){
        if((recvbytes=recv(acceptfd,filename,N,0))==-1){
            ERRLOG("recv error");
        }else if(recvbytes==0){
            printf("client:[%s][%d] 断开连接\n",inet_ntoa(clientaddr.sin_addr),ntohs(clientaddr.sin_port));
            close(acceptfd);
            goto out;
        }
        
        printf("filename:%s\n",filename);

        if((fd=open(filename,O_RDONLY))==-1){
            if(errno==2){
                if(send(acceptfd,"NOEXITS",N,0)==-1){
                    ERRLOG("send error");
                }
                close(fd);
                continue;
            }else{
                ERRLOG("open error");
            }
        }

        if(send(acceptfd,"EXIST",N,0)==-1){
            ERRLOG("send error");
        }

        while((readbytes=read(fd,buf,N))!=0){
            if(send(acceptfd,buf,readbytes,0)==-1){
                ERRLOG("send error");
            }
        }

        sleep(1);

        if(send(acceptfd,"SUCCESS",N,0)==-1){
            ERRLOG("send error");
        }

        printf("文件发送完成");
        close(fd);
    }
    return 0;
}
